<template>
  <el-dialog v-model="dialogVisible" :title="title" width="500" align-center :before-close="closeDialog">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto">
      <el-form-item label="分组名称" prop="name">
        <el-input v-model="ruleForm.name" clearable placeholder="请输入分组名称" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="submitHandler">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, getCurrentInstance } from 'vue';
const dialogVisible = ref(false);
const ruleFormRef = ref(null);
const { proxy } = getCurrentInstance();
const ruleForm = ref({
  name: ''
}); // 表单数据
const rules = ref({
  name: [
    { required: true, message: '请输入分组名称', trigger: 'blur' },
  ]
})
const title = ref('添加分组');
const openDialog = (data) => {
  if (data?.id) {
    title.value = '编辑分组';
  } else {
    title.value = '添加分组';
  }
  dialogVisible.value = true;
}
const closeDialog = () => {
  dialogVisible.value = false;
  ruleFormRef.value.resetFields();
}
const submitHandler = () => {
  ruleFormRef.value.validate(valid => {
    if (valid) {
      if (ruleForm.value.id != undefined) {
        proxy.$modal.msgSuccess("修改成功");
        closeDialog();
      } else {
        closeDialog();
        proxy.$modal.msgSuccess("添加成功");
      }
    }
  });
}
// 将方法暴露给父组件
defineExpose({
  openDialog,
  submitHandler
});
</script>